﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Model.Interfaces;

namespace View.Students
{
    /// <summary>
    /// Interaction logic for StudentPanel.xaml
    /// </summary>
    public partial class StudentPanel : IModel
    {
        public event EventHandler InputAddressEvent;
        public event EventHandler UpdateModelEvent;
        public event EventHandler CancelStudentFormEvent;
        public event EventHandler<Model.ModelEventArgs.StudentEventArgs> SubmitStudentChangesEvent;
        public event EventHandler<Model.ModelEventArgs.StudentEventArgs> AddNewStudentEvent;

        public StudentPanel(IStudent student)
        {
            InitializeComponent();
            this.DataContext = student;
        }

        public StudentPanel()
        {
            InitializeComponent();
        }

        private void applyChangesButton_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateStudentFields())
            {
                Model.ModelClasses.Student updatedStudent = new Model.ModelClasses.Student();
                Model.ModelClasses.PersonContactInformation contInf = new Model.ModelClasses.PersonContactInformation
                {
                    AdditionalPhone = additional.Text,
                    Email = email.Text,
                    LandlinePhone = home.Text,
                    MobilePhone = mobile.Text
                };
                updatedStudent.ContactInformation = contInf;
                updatedStudent.Birthday = (DateTime)date.SelectedDate;
                updatedStudent.FatherName = patronymic.Text;
                updatedStudent.Name = name.Text;
                updatedStudent.FamilyName = lastname.Text;

                if (SubmitStudentChangesEvent != null)
                    SubmitStudentChangesEvent(this, new Model.ModelEventArgs.StudentEventArgs(updatedStudent));
            }
            else
                MessageBox.Show("Заполните недостающие поля");
        }

        /// <summary>
        /// Method validate inserted fields. And highligth incorrect inputs.
        /// </summary>
        /// <returns>Return true if all fieldss is valid</returns>
        private bool ValidateStudentFields()
        {
            Boolean ok = true;
            if (lastname.Text.Equals(""))
            {
                lastname.Background = Brushes.IndianRed;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Заполните поле!";
                lastname.ToolTip = tooltip;
                ok = false;
            }
            else
            {
                lastname.Background = SystemColors.WindowBrush;
                lastname.ToolTip = null;

            }


            if (name.Text.Equals(""))
            {
                name.Background = Brushes.IndianRed;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Заполните поле!";
                name.ToolTip = tooltip;
                ok = false;
            }
            else
            {
                name.Background = SystemColors.WindowBrush;
                name.ToolTip = null;
            }


            if (patronymic.Text.Equals(""))
            {
                patronymic.Background = Brushes.IndianRed;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Заполните поле!";
                patronymic.ToolTip = tooltip;
                ok = false;
            }
            else
            {
                patronymic.Background = SystemColors.WindowBrush;
                patronymic.ToolTip = null;
            }


            if (date.Text != null && date.Text.Equals(""))
            {
                date.Background = Brushes.IndianRed;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Заполните поле!";
                date.ToolTip = tooltip;
                ok = false;
            }
            else
            {
                date.Background = SystemColors.WindowBrush;
                date.ToolTip = null;
            }


            if (mobile.Text.Equals("") && home.Text.Equals("") && additional.Text.Equals(""))
            {
                if (ok) MessageBox.Show("Заполните хотя бы один из номеров!");
                mobile.Background = Brushes.Goldenrod;
                home.Background = Brushes.Goldenrod;
                additional.Background = Brushes.Goldenrod;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Заполните одно из полей!";
                mobile.ToolTip = tooltip;
                home.ToolTip = tooltip;
                additional.ToolTip = tooltip;
                ok = false;
            }
            else
            {
                mobile.Background = SystemColors.WindowBrush;
                home.Background = SystemColors.WindowBrush;
                additional.Background = SystemColors.WindowBrush;

                mobile.ToolTip = null;
                home.ToolTip = null;
                additional.ToolTip = null;

            }

            return ok;
        }

        private void inputAddressButtonClick(object sender, RoutedEventArgs e)
        { 
            if (InputAddressEvent != null) 
                InputAddressEvent(this, new EventArgs()); 
        }

        private Boolean checkIllegalSymbols(string str)
        {
            Regex nameChecker = new Regex(@"^([A-Za-zА-Яа-яїієЇЄІ']+[\s-]?)*[A-Za-zА-Яа-яїієЇЄІ']+$");
            return nameChecker.IsMatch(str);
        }

        private void Names_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox textbox = (TextBox)sender;
            if (!textbox.Text.Equals("") && !checkIllegalSymbols(textbox.Text))
            {
                textbox.Background = Brushes.Gold;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Поле содержит недопустимый символ!";
                textbox.ToolTip = tooltip;
            }
            else
            {
                int t = textbox.SelectionStart;
                string text = "";
                for (int i = 0; i < textbox.Text.Length; i++)
                {
                    if (i == 0 || (i > 0 && textbox.Text[i - 1].Equals('-')))
                    {
                        text += Char.ToUpper(textbox.Text[i]);
                    }
                    else text += textbox.Text[i];
                }
                textbox.Text = text;
                textbox.SelectionStart = t;
                textbox.Background = SystemColors.WindowBrush;
                textbox.ToolTip = null;
            }

        }
        private void Email_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox textbox = (TextBox)sender;
            Regex emailChecker = new Regex(@"^[.-_A-Za-z0-9]+@([A-Za-z0-9][-A_Za-z0-9]+.)+[A_Za-z]{2,6}$");
            if (!textbox.Text.Equals("") && !emailChecker.IsMatch(textbox.Text))
            {
                textbox.Background = Brushes.Gold;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Невалидный e-mail!";
                textbox.ToolTip = tooltip;
            }
            else
            {
                textbox.Background = SystemColors.WindowBrush;
                textbox.ToolTip = null;
            }
        }

        private void Phones_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox textbox = (TextBox)sender;
            Regex phoneChecker = new Regex(@"^\+?\s?(\d+\s?-?\s?)*(\(\d+\)\s?)?(\d+\s?-?\s?)*\d+$");
            if (!textbox.Text.Equals("") && !phoneChecker.IsMatch(textbox.Text))
            {
                textbox.Background = Brushes.Gold;
                ToolTip tooltip = new ToolTip();
                tooltip.Content = "Возможно неверный номер!";
                textbox.ToolTip = tooltip;
            }
            else
            {
                textbox.Background = SystemColors.WindowBrush;
                textbox.ToolTip = null;


            }
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox textbox = (TextBox)sender;
            if (textbox.Text.Length != 0)
            {
                string tempnumber = textbox.Text;
                tempnumber = tempnumber.Replace(" ", "");
                tempnumber = tempnumber.Replace("-", "");
                tempnumber = tempnumber.Replace("(", "");
                tempnumber = tempnumber.Replace(")", "");
                tempnumber = tempnumber.Replace("+", "");
                switch (tempnumber.Length)
                {
                    case 6:
                        tempnumber = tempnumber.Insert(4, "-");
                        tempnumber = tempnumber.Insert(2, "-");
                        textbox.Text = tempnumber;
                        break;
                    case 7:
                        tempnumber = tempnumber.Insert(5, "-");
                        tempnumber = tempnumber.Insert(3, "-");
                        textbox.Text = tempnumber;
                        break;
                    case 10:
                        tempnumber = tempnumber.Insert(8, "-");
                        tempnumber = tempnumber.Insert(6, "-");
                        tempnumber = tempnumber.Insert(3, ") ");
                        tempnumber = tempnumber.Insert(0, "(");
                        textbox.Text = tempnumber;
                        break;
                    case 12:
                        tempnumber = tempnumber.Insert(10, "-");
                        tempnumber = tempnumber.Insert(8, "-");
                        tempnumber = tempnumber.Insert(5, ") ");
                        tempnumber = tempnumber.Insert(2, " (");
                        tempnumber = tempnumber.Insert(0, "+");
                        textbox.Text = tempnumber;
                        break;
                    case 11:
                        tempnumber = tempnumber.Insert(9, "-");
                        tempnumber = tempnumber.Insert(7, "-");
                        tempnumber = tempnumber.Insert(4, ") ");
                        tempnumber = tempnumber.Insert(1, " (");
                        tempnumber = tempnumber.Insert(0, "+");
                        textbox.Text = tempnumber;
                        break;
                    default:
                        break;
                }
            }
        }

        public void UpdateModel() 
        { 
            if (UpdateModelEvent != null) 
                UpdateModelEvent(this, new EventArgs()); 
        }

        public void UpdateModel(object sender, EventArgs eventArgs) 
        {
            if (UpdateModelEvent != null) 
            UpdateModelEvent(sender, eventArgs); 
        }

        private void Lastname_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) { name.Focus(); }
        }

        private void Name_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) { patronymic.Focus(); }
        }

        private void Patronymic_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) date.Focus();
        }

        private void date_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter))
            {
                inputAddressButton.Focus();
                //  RoutedEventArgs r = new RoutedEventArgs(inputAddressButton);
                inputAddressButtonClick(this, new RoutedEventArgs());
            }
        }

        private void mobile_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) home.Focus();
        }

        private void email_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) mobile.Focus();
        }

        private void home_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter)) additional.Focus();
        }

        private void additional_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Enter))
            {
                privilege.Focus();

            }

        }

        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if(DataContext!=null)
            group.ItemsSource = ((IStudent)DataContext).Groups;

        }

        private void saveNewStudentButton_Click(object sender, RoutedEventArgs e)
        {
            if (ValidateStudentFields())
            {
                if (AddNewStudentEvent != null)
                {
                    Model.ModelClasses.Student updatedStudent = new Model.ModelClasses.Student();
                    Model.ModelClasses.PersonContactInformation contInf = new Model.ModelClasses.PersonContactInformation
                    {
                        AdditionalPhone = additional.Text,
                        Email = email.Text,
                        LandlinePhone = home.Text,
                        MobilePhone = mobile.Text
                    };
                    updatedStudent.ContactInformation = contInf;
                    updatedStudent.Birthday = (DateTime)date.SelectedDate;
                    updatedStudent.FatherName = patronymic.Text;
                    updatedStudent.Name = name.Text;
                    updatedStudent.FamilyName = lastname.Text;

                    if (AddNewStudentEvent != null)
                        AddNewStudentEvent(this, new Model.ModelEventArgs.StudentEventArgs(updatedStudent));
                }
            }
        }

        private void cancelStudentButton_Click(object sender, RoutedEventArgs e)
        {
            if (CancelStudentFormEvent != null)
                CancelStudentFormEvent(this, new EventArgs());
        }

    }

}
